//201902104011 王雪梦
package bysj.service;
import bysj.dao.SchoolDao;
import bysj.domain.School;
import util.BysjException;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class SchoolService {
	private static SchoolDao schoolDao= SchoolDao.getInstance();
	private static SchoolService schoolService = null;

	public static SchoolService getInstance(){
		if(schoolService==null){
			schoolService = new SchoolService();
		}
		return schoolService;
	}

	public Collection<School> findAll(List<Condition>conditionList, Pagination pagination) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		Collection<School> schools = schoolDao.findAll(connection,conditionList,pagination);
		JdbcHelper.close(connection);
		return  schools;
	}
	
	public School find(Integer id) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		School school = schoolDao.find(id,connection);
		JdbcHelper.close(connection);
		return school;
	}

	public boolean update(School school) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		boolean updated = schoolDao.update(school,connection);
		JdbcHelper.close(connection);
		return updated;
	}
	
	public Integer add(School school) throws SQLException {
		Connection connection = JdbcHelper.getConn();
		int id = schoolDao.add(school,connection);
		JdbcHelper.close(connection);
		return id;
	}

	public boolean delete (int id) throws SQLException, BysjException {
		Connection connection = JdbcHelper.getConn();
		School school = schoolDao.find(id,connection);
		JdbcHelper.close(connection);
		boolean deleted = this.delete(school);
		return deleted;
	}
	public boolean delete (School school) throws SQLException, BysjException {
		Connection connection = JdbcHelper.getConn();
		int countDepartmentsOfSchool = DepartmentService.getInstance().countAll(school);
		System.out.println(countDepartmentsOfSchool);
		if(countDepartmentsOfSchool==0){
			boolean deleted = schoolDao.delete(school.getId(),connection);
			return  deleted;
		}else{
			throw new BysjException(school.getDescription()+"仍有下属系,不能删除");
		}
	}
}
